package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.entity.SaleBoutique1;
import com.example.demo.entity.SaleBoutique2;
import com.example.demo.form.SaleBoutiqueForm;
import com.example.demo.service.SaleBoutique1Service;
import com.example.demo.service.SaleBoutique2Service;

@RestController
@RequestMapping(value = "/saleBoutique")
public class SaleBoutiqueController1 {
	
	@Autowired 
	private SaleBoutique1Service saleBoutique1DAO;
	
	@Autowired
	private SaleBoutique2Service saleBoutique2DAO;
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
	
	@RequestMapping(value = "/save")
	private Object save(SaleBoutiqueForm Form) throws ParseException {
		Integer saleId1 = Form.getId();
		Date d= new Date();
		Date d1 = dateFormat1.parse("1999-01-01");
		SaleBoutique1 sale1= new SaleBoutique1();
		SaleBoutique1 Sale1= new SaleBoutique1();
		SaleBoutique2 sale2= new SaleBoutique2();
		SaleBoutique2 Sale2= new SaleBoutique2();
		if(saleId1==null) {
			Sale1.setName(Form.getName());
			sale1 = saleBoutique1DAO.save(Sale1);
		}else {
			 sale1 = saleBoutique1DAO.findById(saleId1);
			 sale1.setName(Form.getName());
			 saleBoutique1DAO.save(sale1);
				List<SaleBoutique2> list = saleBoutique2DAO.findBySaleBoutique(sale1);
				for (SaleBoutique2 saleBoutique2 : list) {
					if(d1.compareTo(saleBoutique2.getStartDays())==-1) {
						d1=saleBoutique2.getStartDays();
						Sale2=saleBoutique2;
					}
				}
				Sale2.setEndDays(d);
				saleBoutique2DAO.save(Sale2);
				
		}
		BeanUtils.copyProperties(Form, sale2, "id","name");
		sale2.setSaleBoutique(sale1);
		sale2.setStartDays(d);
		saleBoutique2DAO.save(sale2);
		return new AjaxResult("数据保存成功");			
	}
	
	@RequestMapping(value = "/list")
	public Object list() {
		return new AjaxResult(saleBoutique1DAO.findAll());
	}
	
	@RequestMapping(value = "/findById")
	public Object findbyId(Integer id) throws ParseException {
		List<SaleBoutique2> list = saleBoutique2DAO.findBySaleBoutique(saleBoutique1DAO.findById(id));
		Date d = dateFormat1.parse("1999-01-01");
		SaleBoutique2 n= new SaleBoutique2();
		for (SaleBoutique2 saleBoutique2 : list) {
			if(d.compareTo(saleBoutique2.getStartDays())==-1) {
				d=saleBoutique2.getStartDays();
			    n=saleBoutique2;
			}
		}
		 return new AjaxResult(n);		
	}

	
}
